package com.wzc.bigevent.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wzc.bigevent.mapper.ArticleMapper;
import com.wzc.bigevent.pojo.Article;
import com.wzc.bigevent.pojo.PageBean;
import com.wzc.bigevent.service.ArticleService;
import com.wzc.bigevent.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import javax.xml.transform.Result;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Resource
    private ArticleMapper articleMapper;

    /**
     * 添加文章
     * @param article
     */
    @Override
    public void addArticle(Article article) {
        //1. 获取当前登录用户
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");

        //2. 封装数据
        article.setCreateUser(userId);
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());

        //3. 保存
        articleMapper.add(article);
    }

    /**
     * 根据id获取文章详情
     * @param id
     * @return
     */
    @Override
    public Article getArticleDetail(Integer id) {
        // 根据id获取文章详情
        return articleMapper.getArticleById(id);
    }

    /**
     * 更新文章
     * @param article
     */
    @Override
    public void updateArticle(Article article) {
        // 更新文章
        articleMapper.update(article);
    }

    /**
     * 删除文章
     * @param id
     */
    @Override
    public void deleteArticle(Integer id) {
        // 删除文章
        articleMapper.delete(id);
    }


    /**
     * 分页查询文章列表
     * @param
     * @return
     */
    @Override
    public PageBean<Article> getArticleList(Integer pageNum, Integer pageSize, String state ,Integer categoryId) {
        // 获取当前登录用户
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");

        // 构建PageBean对象
        PageBean<Article> pb = new PageBean<>();

        // 开启分页查询 pageHelper
        PageHelper.startPage(pageNum, pageSize);

        // 调用mapper方法
        Page<Article> page = articleMapper.getList(categoryId,state,userId);
        // 封装数据
        pb.setTotal(page.getTotal());
        pb.setItems(page.getResult());

        return pb;
    }

}
